<template>
  <div class="page-container">
    <a-card>
      <!-- 搜索表单 -->
      <div class="search-form">
        <a-form layout="inline" @finish="handleSearch">
          <a-form-item>
            <a-input
              v-model:value="searchParams.schoolName"
              placeholder="请输入学校名称"
              allowClear
              style="width: 200px"
            >
              <template #prefix>
                <BankOutlined />
              </template>
            </a-input>
          </a-form-item>

          <a-form-item>
            <a-input
              v-model:value="searchParams.campuses"
              placeholder="请输入校区"
              allowClear
              style="width: 200px"
            >
              <template #prefix>
                <EnvironmentOutlined />
              </template>
            </a-input>
          </a-form-item>

          <a-form-item>
            <a-select
              v-model:value="searchParams.schoolStatus"
              placeholder="学校状态"
              allowClear
              style="width: 150px"
            >
              <a-select-option value="active">激活</a-select-option>
              <a-select-option value="inactive">未激活</a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item>
            <a-space>
              <PermissionButton permission="school:list:search">
                <a-button type="primary" html-type="submit" :loading="loading">
                  <SearchOutlined />
                  搜索
                </a-button>
              </PermissionButton>

              <PermissionButton permission="school:list:reset">
                <a-button @click="handleReset">
                  <ReloadOutlined />
                  重置
                </a-button>
              </PermissionButton>
            </a-space>
          </a-form-item>
        </a-form>
      </div>

      <!-- 操作按钮区 -->
      <div class="action-bar">
        <a-space>
          <PermissionButton permission="school:list:add">
            <a-button type="primary" @click="handleAdd">
              <PlusOutlined />
              新增学校
            </a-button>
          </PermissionButton>
        </a-space>
      </div>

      <!-- 学校表格 -->
      <a-table
        :columns="columns"
        :data-source="schoolList"
        :loading="loading"
        :pagination="pagination"
        row-key="id"
        @change="handleTableChange"
        size="middle"
        :scroll="{ x: 1140, y: 600 }"
        class="school-table"
      >
        <!-- 学校Logo列 -->
        <template #schoolAvatar="{ record }">
          <div class="logo-container">
            <a-avatar
              :src="record.schoolAvatar"
              :size="60"
              shape="square"
              @click="handlePreviewImage(record.schoolAvatar)"
              class="school-logo"
            >
              <template #icon>
                <BankOutlined style="font-size: 24px" />
              </template>
            </a-avatar>
          </div>
        </template>

        <!-- 学校名称列 -->
        <template #schoolName="{ record }">
          <div class="school-name-cell">
            <a-typography-text
              :content="record.schoolName"
              :ellipsis="{ tooltip: true }"
              class="school-name-text clickable"
              @click="handleShowSchoolDetail(record)"
            >
              {{ record.schoolName }}
            </a-typography-text>
          </div>
        </template>

        <!-- 校区列 -->
        <template #campuses="{ record }">
          <div class="campus-container">
            <a-tag v-if="record.campuses && record.campuses.trim()" color="blue" class="campus-tag">
              {{ record.campuses }}
            </a-tag>
            <span v-if="!record.campuses || !record.campuses.trim()" class="text-gray">
              暂无校区信息
            </span>
          </div>
        </template>

        <!-- 学校管理员列 -->
        <template #schoolAdmins="{ record }">
          <div class="school-admins-container">
            <template v-if="record.schoolAdmins && record.schoolAdmins.length > 0">
              <!-- 当管理员数量较少时，显示所有管理员 -->
              <template v-if="record.schoolAdmins.length <= 3">
                <a-tag
                  v-for="(admin, index) in record.schoolAdmins"
                  :key="index"
                  color="blue"
                  class="admin-tag"
                >
                  <user-outlined />
                  {{ admin }}
                </a-tag>
              </template>

              <!-- 当管理员数量较多时，显示前2个+更多 -->
              <template v-else>
                <a-tag
                  v-for="(admin, index) in record.schoolAdmins.slice(0, 2)"
                  :key="index"
                  color="blue"
                  class="admin-tag"
                >
                  <user-outlined />
                  {{ admin }}
                </a-tag>
                <a-tooltip
                  :title="`还有${record.schoolAdmins.length - 2}位管理员：${record.schoolAdmins
                    .slice(2)
                    .join('、')}`"
                >
                  <a-tag color="geekblue" class="admin-tag more-tag">
                    +{{ record.schoolAdmins.length - 2 }}位
                  </a-tag>
                </a-tooltip>
              </template>
            </template>

            <!-- 无管理员状态 -->
            <template v-else>
              <a-tag color="default" class="admin-tag empty-tag">
                <exclamation-circle-outlined />
                暂无管理员
              </a-tag>
            </template>
          </div>
        </template>

        <!-- 学校状态列 -->
        <template #schoolStatus="{ record }">
          <div class="status-container">
            <a-tag v-if="record.schoolStatus === 'active'" color="success" class="status-tag">
              <template #icon>
                <CheckCircleOutlined />
              </template>
              正常运营
            </a-tag>
            <a-tag v-else-if="record.schoolStatus === 'inactive'" color="error" class="status-tag">
              <template #icon>
                <CloseCircleOutlined />
              </template>
              暂停运营
            </a-tag>
            <a-tag v-else color="default" class="status-tag">
              {{ record.schoolStatus == 'active' ? '正常运营' : '暂停运营' }}
            </a-tag>
          </div>
        </template>

        <!-- 地理位置列 -->
        <template #location="{ record }">
          <div v-if="record.longitude && record.latitude" class="location-cell">
            <a-button type="link" size="small" @click="handleShowMap(record)" class="location-btn">
              <EnvironmentOutlined />
              查看位置
            </a-button>
            <div class="coordinates-text">
              {{ record.longitude.toFixed(4) }}, {{ record.latitude.toFixed(4) }}
            </div>
          </div>
          <span v-else class="text-gray">未设置位置</span>
        </template>

        <!-- 创建时间列 -->
        <template #createdTime="{ record }">
          <div class="time-cell">
            <a-typography-text type="secondary" class="time-text">
              {{ record.createdTime || record.createTime }}
            </a-typography-text>
          </div>
        </template>

        <!-- 操作列 -->
        <template #action="{ record }">
          <a-space size="small">
            <PermissionButton permission="school:list:edit">
              <a-button type="link" size="small" @click="handleEdit(record)" class="action-btn">
                <EditOutlined />
                编辑
              </a-button>
            </PermissionButton>

            <PermissionButton permission="school:list:delete">
              <a-button
                type="link"
                size="small"
                danger
                @click="handleDelete(record)"
                class="action-btn"
              >
                <DeleteOutlined />
                删除
              </a-button>
            </PermissionButton>
          </a-space>
        </template>
      </a-table>
    </a-card>

    <!-- 新增/编辑学校弹窗 -->
    <a-modal
      v-model:open="modalVisible"
      :title="modalType === 'add' ? '新增学校' : '编辑学校'"
      :confirm-loading="confirmLoading"
      @ok="handleSubmit"
      @cancel="handleCancel"
      width="900px"
    >
      <a-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 19 }"
        class="school-form"
      >
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item label="学校名称" name="schoolName">
              <a-input v-model:value="formData.schoolName" placeholder="请输入学校名称" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="校区" name="campuses">
              <a-input v-model:value="formData.campuses" placeholder="请输入校区名称" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item label="学校状态" name="schoolStatus">
              <a-select v-model:value="formData.schoolStatus" placeholder="请选择学校状态">
                <a-select-option value="active">正常运营</a-select-option>
                <a-select-option value="inactive">暂停运营</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="学校头像" name="schoolAvatar">
              <div class="avatar-upload-container">
                <!-- 没有头像时显示上传按钮 -->
                <div v-if="!formData.schoolAvatar && !uploadLoading" class="upload-btn-container">
                  <a-upload
                    :before-upload="handleBeforeUpload"
                    :show-upload-list="false"
                    accept="image/*"
                    class="avatar-uploader"
                  >
                    <div
                      class="upload-area"
                      :style="{
                        width: '100px',
                        height: '100px',
                        border: '2px dashed #d9d9d9',
                        borderRadius: '8px',
                        display: 'flex',
                        flexDirection: 'column',
                        alignItems: 'center',
                        justifyContent: 'center',
                        cursor: 'pointer',
                        background: '#fafafa',
                        transition: 'all 0.3s ease',
                      }"
                    >
                      <PlusOutlined
                        class="upload-plus"
                        :style="{ fontSize: '24px', color: '#999', marginBottom: '8px' }"
                      />
                      <div
                        class="upload-text"
                        :style="{ fontSize: '14px', color: '#666', fontWeight: '400' }"
                      >
                        Upload
                      </div>
                    </div>
                  </a-upload>
                </div>

                <!-- 上传中显示进度 -->
                <div v-if="uploadLoading" class="upload-progress-container">
                  <div class="progress-area">
                    <a-spin size="large" />
                    <div class="progress-text">{{ uploadProgress }}%</div>
                  </div>
                </div>

                <!-- 上传成功显示头像 -->
                <div
                  v-if="formData.schoolAvatar && !uploadLoading"
                  class="avatar-preview-container"
                >
                  <div
                    class="image-preview"
                    @mouseenter="showDeleteBtn = true"
                    @mouseleave="showDeleteBtn = false"
                    :style="{
                      position: 'relative',
                      display: 'inline-block',
                      cursor: 'pointer',
                      width: '100px',
                      height: '100px',
                    }"
                  >
                    <img
                      :src="formData.schoolAvatar"
                      alt="school avatar"
                      class="preview-image"
                      :style="{
                        width: '100%',
                        height: '100%',
                        objectFit: 'cover',
                        borderRadius: '8px',
                        border: '2px solid #f0f0f0',
                        transition: 'all 0.3s ease',
                      }"
                    />
                    <!-- 操作按钮遮罩 -->
                    <div
                      v-show="showDeleteBtn"
                      class="action-overlay"
                      :style="{
                        position: 'absolute',
                        top: '0',
                        left: '0',
                        right: '0',
                        bottom: '0',
                        background: 'rgba(0, 0, 0, 0.6)',
                        borderRadius: '8px',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        transition: 'all 0.3s ease',
                      }"
                    >
                      <div
                        class="action-buttons"
                        :style="{
                          display: 'flex',
                          gap: '16px',
                        }"
                      >
                        <div
                          class="action-btn preview-btn"
                          @click="handlePreviewImage(formData.schoolAvatar)"
                          :style="{
                            width: '32px',
                            height: '32px',
                            borderRadius: '50%',
                            background: 'rgba(255, 255, 255, 0.9)',
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center',
                            cursor: 'pointer',
                            transition: 'all 0.3s ease',
                            color: '#666',
                          }"
                          @mouseenter="handlePreviewBtnHover"
                          @mouseleave="handlePreviewBtnLeave"
                        >
                          <EyeOutlined :style="{ fontSize: '16px' }" />
                        </div>
                        <div
                          class="action-btn delete-btn"
                          @click="handleRemoveAvatar"
                          :style="{
                            width: '32px',
                            height: '32px',
                            borderRadius: '50%',
                            background: 'rgba(255, 255, 255, 0.9)',
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center',
                            cursor: 'pointer',
                            transition: 'all 0.3s ease',
                            color: '#666',
                          }"
                          @mouseenter="handleDeleteBtnHover"
                          @mouseleave="handleDeleteBtnLeave"
                        >
                          <DeleteOutlined :style="{ fontSize: '16px' }" />
                        </div>
                      </div>
                    </div>
                  </div>
                </div>

                <div class="upload-tip">支持 JPG/PNG/GIF/WEBP 格式，自动压缩优化</div>
              </div>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item label="经度" name="longitude">
              <a-input-number
                v-model:value="formData.longitude"
                placeholder="请输入经度"
                :precision="6"
                :min="-180"
                :max="180"
                style="width: 100%"
                readonly
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="纬度" name="latitude">
              <a-input-number
                v-model:value="formData.latitude"
                placeholder="请输入纬度"
                :precision="6"
                :min="-90"
                :max="90"
                style="width: 100%"
                readonly
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item label="学校地址" name="address">
              <a-input
                v-model:value="formData.address"
                placeholder="选择位置后自动填充"
                readonly
                class="address-input"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="位置选择">
              <a-button @click="handleShowLocationPicker" type="dashed" block class="location-btn">
                <EnvironmentOutlined />
                在地图上选择位置
              </a-button>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>

    <!-- 地图展示弹窗 -->
    <a-modal
      v-model:open="mapVisible"
      :title="`学校位置 - ${selectedSchool?.schoolName || ''}`"
      :footer="null"
      width="800px"
      @after-close="handleMapModalClose"
    >
      <div class="map-container">
        <div id="mapContainer" style="height: 400px; width: 100%"></div>
        <div v-if="selectedSchool" class="location-info">
          <p><strong>学校：</strong>{{ selectedSchool.schoolName }}</p>
          <p>
            <strong>坐标：</strong>{{ selectedSchool.longitude }}, {{ selectedSchool.latitude }}
          </p>
          <p v-if="selectedSchool.address"><strong>地址：</strong>{{ selectedSchool.address }}</p>
        </div>
      </div>
    </a-modal>

    <!-- 位置选择器弹窗 -->
    <a-modal
      v-model:open="locationPickerVisible"
      title="选择学校位置"
      :footer="null"
      width="900px"
      @after-close="handleLocationPickerModalClose"
    >
      <MapLocationPicker
        :visible="locationPickerVisible"
        :initial-location="
          formData.longitude && formData.latitude
            ? { longitude: formData.longitude, latitude: formData.latitude }
            : undefined
        "
        map-height="450px"
        @confirm="handleLocationConfirm"
        @cancel="handleLocationCancel"
      />
    </a-modal>

    <!-- 图片预览 -->
    <a-image-preview-group>
      <a-image
        v-if="previewImage"
        :src="previewImage"
        style="display: none"
        :preview="{ visible: previewVisible, onVisibleChange: handlePreviewVisibleChange }"
      />
    </a-image-preview-group>

    <!-- 学校详情侧边栏 -->
    <SchoolDetailDrawer v-model:visible="schoolDetailVisible" :school-id="selectedSchoolId" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, onUnmounted } from 'vue'
import { message, Modal } from 'ant-design-vue'
import {
  BankOutlined,
  EnvironmentOutlined,
  PlusOutlined,
  SearchOutlined,
  ReloadOutlined,
  UploadOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  EditOutlined,
  DeleteOutlined,
  EyeOutlined,
  UserOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons-vue'
import type { TableColumnsType, FormInstance } from 'ant-design-vue'
import { schoolService } from '@/api/school'
import type { School, SchoolPageParams } from '@/types'
import PermissionButton from '@/components/PermissionButton.vue'
import { createReadonlyMap, destroyMap, type LocationInfo } from '@/utils/mapUtils'
import MapLocationPicker from '@/components/MapLocationPicker.vue'
import SchoolDetailDrawer from '@/components/SchoolDetailDrawer.vue'
import { uploadFile, validateFile, getImagePreviewUrl } from '@/utils/upload'

// 页面状态
const loading = ref(false)
const uploadLoading = ref(false)
const uploadProgress = ref(0)
const schoolList = ref<School[]>([])
const modalVisible = ref(false)
const modalType = ref<'add' | 'edit'>('add')
const confirmLoading = ref(false)
const formRef = ref<FormInstance>()
const mapVisible = ref(false)
const locationPickerVisible = ref(false)
const previewVisible = ref(false)
const previewImage = ref('')
const searchKeyword = ref('')
const showDeleteBtn = ref(false)
const schoolDetailVisible = ref(false)
const selectedSchoolId = ref<number>()

// 地图相关
const selectedSchool = ref<School | null>(null)
let currentMap: any = null

// 搜索参数
const searchParams = reactive<SchoolPageParams>({
  page: 1,
  pageSize: 20,
  schoolName: '',
  campuses: '',
  schoolStatus: undefined,
})

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
})

// 表格列配置
const columns: TableColumnsType = [
  {
    title: '学校Logo',
    dataIndex: 'schoolAvatar',
    key: 'schoolAvatar',
    width: 100,
    align: 'center',
    slots: { customRender: 'schoolAvatar' },
  },
  {
    title: '学校名称',
    dataIndex: 'schoolName',
    key: 'schoolName',
    width: 180,
    ellipsis: true,
    slots: { customRender: 'schoolName' },
  },
  {
    title: '校区',
    dataIndex: 'campuses',
    key: 'campuses',
    width: 120,
    ellipsis: true,
    slots: { customRender: 'campuses' },
  },
  {
    title: '学校管理员',
    dataIndex: 'schoolAdmins',
    key: 'schoolAdmins',
    width: 200,
    slots: { customRender: 'schoolAdmins' },
  },
  {
    title: '状态',
    dataIndex: 'schoolStatus',
    key: 'schoolStatus',
    width: 100,
    align: 'center',
    slots: { customRender: 'schoolStatus' },
  },
  {
    title: '地理位置',
    dataIndex: 'location',
    key: 'location',
    width: 160,
    align: 'center',
    slots: { customRender: 'location' },
  },
  {
    title: '创建时间',
    dataIndex: 'createdTime',
    key: 'createdTime',
    width: 160,
    sorter: true,
    slots: { customRender: 'createdTime' },
  },
  {
    title: '操作',
    key: 'action',
    width: 120,
    align: 'center',
    fixed: 'right',
    slots: { customRender: 'action' },
  },
]

// 表单数据
const formData = reactive<Partial<School & { address?: string }>>({
  schoolName: '',
  campuses: '',
  schoolStatus: 'active',
  schoolAvatar: '',
  longitude: undefined,
  latitude: undefined,
  address: '',
})

// 表单验证规则
const formRules = {
  schoolName: [
    { required: true, message: '请输入学校名称' },
    { min: 2, max: 50, message: '学校名称长度为2-50个字符' },
  ],
  campuses: [{ required: true, message: '请输入校区信息' }],
  schoolStatus: [{ required: true, message: '请选择学校状态' }],
  schoolAvatar: [{ required: true, message: '请上传学校头像' }],
  longitude: [{ type: 'number', min: -180, max: 180, message: '经度范围为-180到180' }],
  latitude: [{ type: 'number', min: -90, max: 90, message: '纬度范围为-90到90' }],
}

// 搜索功能
const handleSearch = () => {
  pagination.current = 1
  searchParams.page = 1
  loadSchoolList()
}

// 重置功能
const handleReset = () => {
  // 重置搜索参数
  searchParams.schoolName = ''
  searchParams.campuses = ''
  searchParams.schoolStatus = undefined

  // 重置分页
  pagination.current = 1
  searchParams.page = 1

  // 重新加载
  loadSchoolList()
  message.success('已重置搜索条件')
}

// 加载学校列表
const loadSchoolList = async () => {
  try {
    loading.value = true
    const params = {
      ...searchParams,
      page: pagination.current,
      pageSize: pagination.pageSize,
    }

    const result = await schoolService.getSchoolPage(params)
    schoolList.value = result.result
    pagination.total = result.total
  } catch (error) {
    message.error('加载学校列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 表格变化处理
const handleTableChange = (pag: any) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  searchParams.page = pag.current
  searchParams.pageSize = pag.pageSize
  loadSchoolList()
}

// 新增学校
const handleAdd = () => {
  modalType.value = 'add'
  modalVisible.value = true
  resetFormData()
}

// 编辑学校
const handleEdit = (record: School) => {
  modalType.value = 'edit'
  modalVisible.value = true
  Object.assign(formData, record)
}

// 删除学校
const handleDelete = (record: School) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除学校 "${record.schoolName}" 吗？`,
    onOk: async () => {
      try {
        await schoolService.deleteSchool(record.id)
        message.success('删除成功')
        loadSchoolList()
      } catch (error) {
        message.error('删除失败')
        console.error(error)
      }
    },
  })
}

// 显示地图
const handleShowMap = async (record: School) => {
  selectedSchool.value = record
  mapVisible.value = true

  await nextTick()
  try {
    currentMap = await createReadonlyMap('mapContainer', {
      longitude: record.longitude,
      latitude: record.latitude,
      title: record.schoolName,
    })
  } catch (error) {
    console.error('地图加载失败:', error)
    message.error('地图加载失败，请检查网络连接')
  }
}

// 显示位置选择器
const handleShowLocationPicker = () => {
  locationPickerVisible.value = true
}

// 位置确认
const handleLocationConfirm = (location: LocationInfo) => {
  formData.longitude = location.longitude
  formData.latitude = location.latitude
  formData.address = location.address
  locationPickerVisible.value = false
  message.success(`已选择位置：${location.name || location.address}`)
}

// 位置取消
const handleLocationCancel = () => {
  locationPickerVisible.value = false
}

// 地图弹窗关闭
const handleMapModalClose = () => {
  destroyMap()
  currentMap = null
}

// 位置选择器弹窗关闭
const handleLocationPickerModalClose = () => {
  destroyMap()
  currentMap = null
}

// 图片预览
const handlePreviewImage = (imageUrl: string) => {
  if (imageUrl) {
    previewImage.value = imageUrl
    previewVisible.value = true
  }
}

// 图片预览可见性变化
const handlePreviewVisibleChange = (visible: boolean) => {
  previewVisible.value = visible
}

// 删除头像
const handleRemoveAvatar = () => {
  formData.schoolAvatar = ''
}

// 按钮悬停效果处理
const handlePreviewBtnHover = (event: Event) => {
  const target = event.target as HTMLElement
  target.style.background = '#fff'
  target.style.transform = 'scale(1.1)'
  target.style.color = '#1890ff'
}

const handlePreviewBtnLeave = (event: Event) => {
  const target = event.target as HTMLElement
  target.style.background = 'rgba(255, 255, 255, 0.9)'
  target.style.transform = 'scale(1)'
  target.style.color = '#666'
}

const handleDeleteBtnHover = (event: Event) => {
  const target = event.target as HTMLElement
  target.style.background = '#fff'
  target.style.transform = 'scale(1.1)'
  target.style.color = '#ff4d4f'
}

const handleDeleteBtnLeave = (event: Event) => {
  const target = event.target as HTMLElement
  target.style.background = 'rgba(255, 255, 255, 0.9)'
  target.style.transform = 'scale(1)'
  target.style.color = '#666'
}

// 文件上传前处理
const handleBeforeUpload = async (file: File) => {
  // 验证文件
  if (!validateFile(file)) {
    return false
  }

  try {
    uploadLoading.value = true
    uploadProgress.value = 0

    const imageUrl = await uploadFile(file, {
      autoCompress: true,
      quality: 0.8,
      maxWidth: 1200,
      maxHeight: 800,
      onProgress: (percent) => {
        uploadProgress.value = percent
      },
      onSuccess: (url) => {
        formData.schoolAvatar = url
        message.success('学校头像上传成功')
      },
      onError: (error) => {
        console.error('上传失败:', error)
        message.error('头像上传失败，请重试')
      },
    })

    if (!imageUrl) {
      throw new Error('上传失败')
    }
  } catch (error) {
    console.error('上传异常:', error)
  } finally {
    uploadLoading.value = false
    uploadProgress.value = 0
  }

  return false // 阻止默认上传
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    confirmLoading.value = true

    // 移除address字段，因为后端接口不需要
    const submitData = { ...formData }
    delete submitData.address

    if (modalType.value === 'add') {
      await schoolService.createSchool(submitData)
      message.success('新增学校成功')
    } else {
      await schoolService.updateSchool(submitData)
      message.success('更新学校成功')
    }

    modalVisible.value = false
    loadSchoolList()
  } catch (error) {
    if (error instanceof Error) {
      message.error(`操作失败: ${error.message}`)
    } else {
      message.error('表单验证失败')
    }
    console.error(error)
  } finally {
    confirmLoading.value = false
  }
}

// 取消操作
const handleCancel = () => {
  modalVisible.value = false
  resetFormData()
}

// 重置表单数据
const resetFormData = () => {
  Object.assign(formData, {
    schoolName: '',
    campuses: '',
    schoolStatus: 'active',
    schoolAvatar: '',
    longitude: undefined,
    latitude: undefined,
    address: '',
  })
  formRef.value?.clearValidate()
}

// 显示学校详情
const handleShowSchoolDetail = (record: School) => {
  selectedSchoolId.value = record.id
  schoolDetailVisible.value = true
}

// 关闭学校详情
const handleSchoolDetailClose = () => {
  schoolDetailVisible.value = false
}

// 页面初始化
onMounted(() => {
  loadSchoolList()
})

// 页面销毁时清理资源
onUnmounted(() => {
  destroyMap()
})
</script>

<style scoped lang="scss">
.page-container {
  padding: 24px;

  .search-form {
    margin-bottom: 16px;
    padding: 16px;
    background: #fafafa;
    border-radius: 8px;
  }

  .action-bar {
    margin-bottom: 16px;
  }

  // 表格样式优化
  .logo-container {
    display: flex;
    justify-content: center;
    align-items: center;

    .school-logo {
      border: 2px solid #f0f0f0;
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        border-color: #1890ff;
        transform: scale(1.05);
      }
    }
  }

  .school-name-cell {
    .school-name-text {
      font-weight: 500;
      color: #262626;
      font-size: 14px;

      &.clickable {
        color: #1890ff;
        cursor: pointer;
        transition: all 0.3s ease;

        &:hover {
          color: #40a9ff;
          text-decoration: underline;
        }
      }
    }
  }

  .campus-container {
    display: flex;
    flex-wrap: wrap;
    gap: 4px;

    .campus-tag {
      margin: 0;
      font-size: 12px;
      border-radius: 2px;
    }
  }

  .school-admins-container {
    display: flex;
    flex-wrap: wrap;
    gap: 4px;
    align-items: center;

    .admin-tag {
      margin: 0;
      font-size: 12px;
      border-radius: 4px;
      display: inline-flex;
      align-items: center;
      padding: 2px 8px;
      line-height: 20px;
      font-weight: 500;
      transition: all 0.3s ease;
      cursor: default;

      :deep(.anticon) {
        margin-right: 4px;
        font-size: 12px;
      }

      &:hover {
        transform: translateY(-1px);
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      }

      &.more-tag {
        background: linear-gradient(135deg, #1890ff, #722ed1);
        border-color: #722ed1;
        color: white;
        font-weight: 600;
        cursor: pointer;

        &:hover {
          background: linear-gradient(135deg, #40a9ff, #9254de);
          transform: translateY(-1px) scale(1.05);
        }
      }

      &.empty-tag {
        background: #f5f5f5;
        color: #999;
        border-color: #d9d9d9;
        font-style: italic;

        :deep(.anticon) {
          color: #faad14;
        }
      }
    }

    // 当容器宽度较小时，调整布局
    @media (max-width: 1200px) {
      .admin-tag {
        font-size: 11px;
        padding: 1px 6px;
        line-height: 18px;

        :deep(.anticon) {
          font-size: 10px;
          margin-right: 2px;
        }
      }
    }
  }

  .status-container {
    .status-tag {
      font-weight: 500;

      :deep(.anticon) {
        margin-right: 4px;
      }
    }
  }

  .location-cell {
    text-align: center;

    .location-btn {
      padding: 0;
      height: auto;
      font-size: 12px;

      :deep(.anticon) {
        margin-right: 4px;
      }
    }

    .coordinates-text {
      font-size: 11px;
      color: #999;
      margin-top: 2px;
      line-height: 1.2;
    }
  }

  .time-cell {
    .time-text {
      font-size: 13px;
    }
  }

  .action-btn {
    padding: 4px 8px;
    height: auto;

    :deep(.anticon) {
      margin-right: 4px;
    }
  }

  .school-name {
    font-weight: 500;
    color: #262626;
    margin-bottom: 4px;
  }

  .school-campus {
    .ant-tag {
      margin-right: 4px;
      margin-bottom: 2px;
    }
  }

  .text-gray {
    color: #999;
    font-size: 12px;
  }

  // 表单样式优化
  .school-form {
    .avatar-upload-container {
      display: flex;
      flex-direction: column;
      align-items: flex-start;

      .upload-btn-container {
        :deep(.avatar-uploader) {
          .ant-upload {
            display: block;
          }
        }

        .upload-area {
          width: 100px;
          height: 100px;
          border: 2px dashed #d9d9d9;
          border-radius: 8px;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          cursor: pointer;
          transition: all 0.3s ease;
          background: #fafafa;

          &:hover {
            border-color: #1890ff;
            background: #f0f8ff;
          }

          .upload-plus {
            font-size: 24px;
            color: #999;
            margin-bottom: 8px;
          }

          .upload-text {
            font-size: 14px;
            color: #666;
            font-weight: 400;
          }
        }
      }

      .upload-progress-container {
        .progress-area {
          width: 100px;
          height: 100px;
          border: 2px dashed #d9d9d9;
          border-radius: 8px;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          background: #fafafa;

          .progress-text {
            font-size: 12px;
            color: #666;
            margin-top: 8px;
          }
        }
      }

      .avatar-preview-container {
        .image-preview {
          position: relative;
          display: inline-block;
          cursor: pointer;
          width: 100px;
          height: 100px;

          .preview-image {
            width: 100%;
            height: 100%;
            object-fit: cover;
            border-radius: 8px;
            border: 2px solid #f0f0f0;
            transition: all 0.3s ease;

            &:hover {
              border-color: #1890ff;
            }
          }

          .action-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.6);
            border-radius: 8px;
            display: flex;
            alignitems: center;
            justifycontent: center;
            transition: all 0.3s ease;

            .action-buttons {
              display: flex;
              gap: 16px;

              .action-btn {
                width: 32px;
                height: 32px;
                border-radius: 50%;
                background: rgba(255, 255, 255, 0.9);
                display: flex;
                alignitems: center;
                justifycontent: center;
                cursor: pointer;
                transition: all 0.3s ease;
                color: #666;

                &:hover {
                  background: #fff;
                  transform: scale(1.1);
                }

                &.preview-btn:hover {
                  color: #1890ff;
                }

                &.delete-btn:hover {
                  color: #ff4d4f;
                }

                :deep(.anticon) {
                  font-size: 16px;
                  margin: 0;
                }
              }
            }
          }
        }
      }

      .upload-tip {
        margin-top: 8px;
        color: #999;
        font-size: 12px;
        line-height: 1.4;
      }
    }

    .address-input {
      background: #f9f9f9;
    }

    .location-btn {
      height: 40px;
      font-size: 14px;

      :deep(.anticon) {
        margin-right: 8px;
      }
    }
  }

  .map-container {
    .location-info {
      margin-top: 16px;
      padding: 12px;
      background: #f0f2f5;
      border-radius: 6px;

      p {
        margin: 4px 0;
      }
    }
  }
}

// 响应式布局
@media (max-width: 768px) {
  .page-container {
    padding: 16px;

    .search-section {
      :deep(.ant-row) {
        flex-direction: column;
        gap: 16px;

        .ant-col {
          width: 100% !important;
          flex: none !important;

          &.text-right {
            text-align: left;
          }
        }
      }
    }

    // 移动端表格优化
    .school-table {
      :deep(.ant-table) {
        .ant-table-thead > tr > th,
        .ant-table-tbody > tr > td {
          padding: 8px 4px;
          font-size: 12px;
        }

        .ant-table-thead > tr > th {
          white-space: normal;
          word-break: break-word;
        }
      }
    }

    // 移动端管理员标签优化
    .school-admins-container {
      .admin-tag {
        font-size: 10px !important;
        padding: 1px 4px !important;
        line-height: 16px !important;

        :deep(.anticon) {
          font-size: 9px !important;
          margin-right: 2px !important;
        }
      }
    }

    // 移动端其他标签优化
    .campus-tag,
    .status-tag {
      font-size: 10px !important;
      padding: 1px 4px !important;
    }
  }
}

// 中等屏幕优化
@media (max-width: 1200px) and (min-width: 769px) {
  .page-container {
    .school-table {
      :deep(.ant-table) {
        .ant-table-thead > tr > th,
        .ant-table-tbody > tr > td {
          padding: 10px 6px;
        }
      }
    }
  }
}
</style>